<?php
// +----------------------------------------------------------------------

// +----------------------------------------------------------------------

namespace Home\Controller;
use Think\Controller;
use Think\Controller\RestController;
use User\Api\UserApi;
use Com\Wechat\JsApiPay;
use Com\Wechat\lib\WxPayUnifiedOrder;
use Com\Wechat\lib\WxPayApi;
use Com\Wechat\lib\WxPayNotify;
use Com\Wechat\Jssdk\Jssdk;
use Think\Log;
/**
 * 收藏模型控制器
 * 
 */
class PayNotifyCallBack extends WxPayNotify
{
  //查询订单
  public function Queryorder($transaction_id)
  {
    return true;
  }

  //重写回调处理函数
  public function NotifyProcess($data, &$msg)
  {

    Log::record("call back:" . json_encode($data),'WARN');
    $notfiyOutput = array();

    if(!array_key_exists("transaction_id", $data)){
      $msg = "输入参数不正确";
      return false;
    }
    //查询订单，判断订单真实性
    if(!$this->Queryorder($data["transaction_id"])){
      $msg = "订单查询失败";
      return false;
    }
    else{
      //判断该笔订单是否在商户网站中已经做过处理
        $out_trade_no = $data["out_trade_no"];
        $order = M('order')->where(array('id'=>$out_trade_no))->find();
            if(!$order){
                die('未找到订单');
            }
            else if($order['status'] == "3") {
                echo '此订单已支付成功';
            }else{
                $data['uid'] =$order['uid'];
                $data['added_date'] =time();
                $data['status'] =1;//付款成功
                $data['order_id'] =$order['id'];
                $data['charge'] =$order['order_price'];
                M('record')->add($data);
                $save['status']=3;
                $order = M('order')
                        ->where(array('id'=>$out_trade_no))
                        ->save($save);
            }
        }
        return true;
    }

  
}
class OrderController extends HomeController {
    
    public $needtime ='2000';//默认2个小时未支付自动取消
    public function index(){

    }

    public function scanOrder(){
       
        $needtime = $this->needtime;
        $nowtime =time();
        $map['status'] = 1;       
        $orders =M('order')->where($map)->select();
        if($orders){
            foreach ($orders as $key => $value) {
                $create_time =$value['date_added'] ; 
                $length =$nowtime-$create_time;//订单生成时间已经过了多长时间
               
                if($length>=$needtime){
                    continue;
                }else{
                    unset($orders[$key]);
                }
              
            }
            $needorders =$orders;
            if($needorders) {
                $need_ids =array_column($needorders,'id');
                $data['is_cancel'] =2;
                $data['status'] =2;//超时未支付自动取消
                $data['cancel_reason'] ="超时未支付自动取消";
                $data['cancel_time'] =$nowtime;
                $auto =M('order')
                        ->where(array('id'=>array('in',$need_ids)))
                        ->save($data);
                echo time()."开始执行订单转换状态";

            }else{
                echo time()."当前时间无超额为夫订单订单";
            }
               
           
        }else {
           echo time()."当前时间无未付款订单";
        }
        
        //$scan_data = M('order')->where($map)->data($data)->save();  
        
    }
    public function autoFinishOrder(){
        $begin_time =time();
        $end_time =$begin_time+24*3600-1;
        $map['status']=array('in','3,5');//已付款（出票中）或者已出票
        $map['tour_time']=array('between',"$begin_time,$end_time");
        $disneydetail =M('disneydetail')
                    ->join('`order` on order.id =disneydetail.order_id')
                    ->where($map)
                    ->select();
        if($disneydetail){
            $ids  =array_column($disneydetail,'id');
            if(!$ids){
                $ids =array(0);
            }
            $status['status']=6;
            $save =M('order')->where(array('id'=>array('in',$ids)))->save($status);
            echo time()."执行订单自动完成";
        }         
        $onedaydetail =M('onedaydetail')
                        ->join('`order` on order.id =onedaydetail.order_id')
                        ->where($map)  
                        ->select();
        if($onedaydetail){
            $need_ids =array_column($onedaydetail,'id');
            if(!$need_ids){
                $need_ids =array(0);
            }
            $status['status']=6;
            $save =M('order')->where(array('id'=>array('in',$need_ids)))->save($status);
            echo time()."执行订单自动完成";
        }

    } 
    //每天18点执行明天的订单取消
    public function autoCancelOrder(){
        $begin = mktime(0,0,0,date('m'),date('d')+1,date('Y'));
        $end = mktime(23,59,59,date('m'),date('d')+1,date('Y'));
        $map =array();
        $map['status'] =1;
        $map['tour_time']=array('between',"$begin_time,$end_time");
        //迪士尼
        $disneydetail =M('disneydetail')
                    ->join('`order` on order.id =disneydetail.order_id')
                    ->where($map)
                    ->select();
        if($disneydetail){
            $ids  =array_column($disneydetail,'id');
            if(!$ids){
                $ids =array(0);
            }
            $status['status']=6;
            $save =M('order')->where(array('id'=>array('in',$ids)))->save($status);
            echo time()."超过18点订单自动取消";
        }
        //一日游         
        $onedaydetail =M('onedaydetail')
                        ->join('`order` on order.id =onedaydetail.order_id')
                        ->where($map)  
                        ->select();
        if($onedaydetail){
            $need_ids =array_column($onedaydetail,'id');
            if(!$need_ids){
                $need_ids =array(0);
            }
            $status['status']=6;
            $save =M('order')->where(array('id'=>array('in',$need_ids)))->save($status);
            echo time()."超过18点订单自动取消";
        }
    }
	public function orderGet(){
        $uid =$this->login();
        $json['success'] = true;
		if(I('get.type') != null){
			$type = I('get.type');
		}else{
			$type = 0;
		}
		if(I('get.order_id') != null){
			$order_id = I('get.order_id');
		}else{
			$order_id = 0;
		}
		
		switch ($type) {
		case '-1':
			//-1,获取指定订单信息
				$filter = array('id' => $order_id,'uid'=>$uid);
				break;
		default:
				//0,获取全部订单信息
				//1,获取未支付订单信息
				//2,获取已支付订单信息
				//3,获取已完成订单信息
                if($type=='0'){
                    $filter = array('is_delete' => 0,'uid'=>$uid);
                }elseif($type=='1'){
                    $filter = array('is_delete' => 0,'status'=>'1','uid'=>$uid);
                }elseif($type=='2'){
                    $filter = array('is_delete' => 0,'status'=>array('in','3,5'),'uid'=>$uid);
                }elseif($type=='3'){
                    $filter = array('is_delete' => 0,'status'=>'6','uid'=>$uid);
                }
				break;
		}

        $order_data = $this->getOrders($filter);

        foreach ($order_data as $key => $value) {
            $order_data[$key]['date_added'] = intval($order_data[$key]['date_added']);
            if($value['project'] == 1){
                $oneday_detail_data = M('onedaydetail')->where('order_id='.$value['id'])->find();
                $oneday_detail_data['tour_time'] =intval($oneday_detail_data['tour_time']);
                $order_data[$key]['onedaydetail'] = $oneday_detail_data;
                $contact_num_data = D('contacts')->getContactNumByOrderId($value['id']);
                $order_data[$key]['contact_num_data'] = $contact_num_data;
            }else{
                $disney_detail_data = M('disneydetail')->where('order_id='.$value['id'])->find();
                $disney_detail_data['tour_time'] =intval($disney_detail_data['tour_time']);
                $order_data[$key]['disneydetail'] = $disney_detail_data;
            }
            $date_pay = M('record')->where('order_id='.$value['id'])->field('added_date')->find();
            $order_data[$key]['date_pay'] = intval($date_pay['added_date']);
        }
        if($order_data){
            foreach ($order_data as $key => $value) {
                if($value['project'] == 1){
                    $articleshow_data = $this->getArticleshowByArticleId($value['article_id']);
                    $order_data[$key]['oneday'] = $articleshow_data;
                }

            $order_data[$key]['contacts'] = $this->getContactsByOrderId($value['id']);  
            if($order_data[$key]['contacts']['0']['tickets']){
                
                $order_data[$key]['contacts']['0']['tickets'] = json_decode($order_data[$key]['contacts']['0']['tickets']);
                }
                

            }

            $json['info'] = $order_data;
        }else{
            $json['success'] = false;
            $json['error'] = '未找到订单'; 
        }
        
        if($json['success']){
            $this->ajaxReturn($json);
        }else{
            $this->ajaxReturn($json,400);
        }
           
		
		
	}

    protected function collectionGet($uid){
        $collection = D('collection');
        $collectiondata = $collection->collectionGet($uid);
        return $collectiondata;
    }


    protected function getArticleshowByArticleId($article_id){
        $articleshowModel = D('articleshow');
        $articleshowdata = $articleshowModel->articleShowGet($article_id);
        $uid = is_login();
        $collectiondata = $this->collectionGet($uid);
        if($collectiondata['success']){
            $collectionArray = $collectiondata['info'];
        }else{
            $collectionArray = array();
        }
        foreach ($articleshowdata as $key => $value) {
            if(in_array($value['id'], $collectionArray)){
                $articleshowdata[$key]['collection'] = true;
            }else{
                $articleshowdata[$key]['collection'] = false;
            }
        }
        foreach ($articleshowdata as $key => $value) {
             $save_data[$key] = array(
            'id' => $value['id'], 
            'title'=>$value['title'], 
            'content' => $value['content'], 
            'description'=>$value['description'], 
            'recommend' => (bool)$value['recommend'], 
            'hot' => (bool)$value['hot'], 
            'magic' => (bool)$value['magic'], 
            'flower' => (bool)$value['flower'], 
            'weekend' => (bool)$value['weekend'], 
            'buffet' => (bool)$value['buffet'], 
            // 'high_price'=>$value['high_price'], 
            // 'low_price' => $value['low_price'], 
            'one_price' =>floatval($value['one_price']),
            'two_price' => floatval($value['two_price']),
            'three_price'=>floatval($value['three_price']),
            'four_price' =>floatval($value['four_price']), 
            'collect_num'=>$value['collect_num'], 
            'collection' =>$value['collection'],
            'epense_explanation'=>$value['epense_explanation'],
            );
             $banners = array();
             $banners =array(
                '0' => $this->imgIdToPicture($articleshowdata[$key]['banner1']), 
                '1' => $this->imgIdToPicture($articleshowdata[$key]['banner2']), 
                '2' => $this->imgIdToPicture($articleshowdata[$key]['banner3']), 
                '3' => $this->imgIdToPicture($articleshowdata[$key]['banner4']), 
                '4' => $this->imgIdToPicture($articleshowdata[$key]['banner5']), 
                );
            $save_banners_data =array();
            foreach ($banners as $key2 => $value2) {
                if($value2){
                    $save_banners_data[] = $value2;  
                }
                
            }

            if($save_banners_data){
                $save_data[$key]['banners'] = $save_banners_data;
            }else{
                $save_data[$key]['banners'] = null;
            }

        }
        return $save_data;
    }

    protected function imgIdToPicture($homepageimgdata){
        if($homepageimgdata){
            $picture = D('picture');
            $imgdata = $picture->getPictureByIds($homepageimgdata);
        }else{
            $imgdata = null;
        }
        
        return $imgdata;
    }

    protected function getContactsByOrderId($order_id){
        $contactsModel = D('contacts');
        $contacts_data = $contactsModel->getcontactsByOrderId($order_id);
        return $contacts_data;
    }

    protected function getOrders($filter){
        $orderModel = D('order');
        $order_data = $orderModel->getOrders($filter);
        return $order_data;
    }

	protected function getOrderByOrderId($uid,$order_id){
        $uid =$this->login();
		$orderModel = D('order');
		$data = $orderModel->orderByOrderIdGet($uid,$order_id);
		return $order_data;
	}
	
 	protected function getOrdersByType($uid,$type){
        $uid =$this->login();
 		$orderModel = D('order');
 		$order_data = $orderModel->getOrdersByType($uid,$type);
 		return $order_data;
 	}
    protected function getPrice($article,$contacts_num){
        $articleshowModel = D('articleshow');
        $price = $articleshowModel->getPrice($article,$contacts_num);
        return $price;
    }

    public function wxpay() {
       
        //根据前台上传的order real id获取订单
        $data =json_decode(file_get_contents('php://input'), true);
        $order_inc_id = $data['order_id'];
        if(!$order_inc_id){
            $this->response(array('info'=>'缺少参数order id'),'json',400);
          //$this->ajaxReturn(array('success'=>'false','error'=>'缺少参数order id'));
        }
        $order = M('order')->where(array('id'=>$order_inc_id))->find();
        if(!$order){
            $this->response(array('info'=>'未查到订单'),'json',400);
            //$this->ajaxReturn(array('success'=>'false','error'=>'未查到订单'));
        }
        if($order['status']=='3'){
            $this->response(array('info'=>'您已经支付过订单了'),'json',400);
            //$this->ajaxReturn(array('success'=>'false','error'=>'您已经支付过订单了'));
        }
        $nowtime =time();
        $deadtime =mktime(18,0,0,date('m'),date('d'),date('Y'));
        // if($order&&$order['project']=='1'&&$nowtime>=$deadtime){
        //     $save['status'] =2;
        //     $save['is_cancel']=2;
        //     $save['cancel_time'] =time();
        //     $save['cancel_reason'] ="一日游超过18点未付款,自动取消";
        //     $order =M('order')->where(array('id'=>$order_inc_id))->save($save);
        //     $this->ajaxReturn(array('success'=>'false','error'=>"该订单未在18点前付款，已经自动取消"));       
        // }
        $notify_url = $this->getReturnUrl('wxNotify');
        //①、获取用户openid
        $tools = new JsApiPay();
        $uid = $this->login();
        $member =M('ucenter_member')->where(array('id'=>$uid,'status'=>1))->find();
        if(!$member['openid']) {
            $this->response(array('info'=>'请在微信端打开'),'json',400);
            //$this->ajaxReturn(array('info'=>'请在微信端打开'));
        }
            // $openId = $tools->GetOpenid();
            $openId = $member['openid'];
        //②、统一下单
        $out_trade_no = $order['id'];
        $input = new WxPayUnifiedOrder();
        $input->SetBody("旅游支付 - ".$out_trade_no);
        $input->SetOut_trade_no($out_trade_no);
        $input->SetTotal_fee(intval($order['order_price']*100));
        $input->SetTime_start(date("YmdHis"));
        $input->SetTime_expire(date("YmdHis", time() + 600));
        $input->SetNotify_url($notify_url);
        $input->SetTrade_type("JSAPI");
        $input->SetOpenid($openId);
        $order = WxPayApi::unifiedOrder($input);
        $jsApiParameters = $tools->GetJsApiParameters($order);
        \Think\Log::record($jsApiParameters,'WARN');
        $this->response($jsApiParameters,'');
    }

    public function getReturnUrl($actionKey){
    $sys_protocal = isset($_SERVER['SERVER_PORT']) && $_SERVER['SERVER_PORT'] == '443' ? 'https://' : 'http://';
    $php_self = $_SERVER['PHP_SELF'] ? $_SERVER['PHP_SELF'] : $_SERVER['SCRIPT_NAME'];
    $path_info = isset($_SERVER['PATH_INFO']) ? $_SERVER['PATH_INFO'] : '';
    $relate_url = isset($_SERVER['REQUEST_URI']) ? $_SERVER['REQUEST_URI'] : $php_self.(isset($_SERVER['QUERY_STRING']) ? '?'.$_SERVER['QUERY_STRING'] : $path_info);
    $result = $sys_protocal.(isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : '').$relate_url;
    $result =  explode('/', $result);
    array_splice($result, -1, 1, $actionKey);
    $return_url = implode('/', $result);
        return $return_url;
    }

     public function wxNotify(){
        Log::record('begin notify','WARN');
        $notify = new PayNotifyCallBack();
        $notify->Handle(false);
    }
    
    

    public function orderCancel(){
        $uid =$this->login();
        $post =json_decode(file_get_contents('php://input'), true);
        // $post['order_id']=19;//
        if($post['order_id']!= null){
            $order_id = $post['order_id'];
        }else{
            $order_id = 0;
        }
        $order =M('order')->find($order_id);

        if(!(($order['status']=='3'||$order['status']=='5')&&($order['project']==2))){
            $orderModel =D('Order');
    
            $order_data = $orderModel->cancelOrder($uid,$order_id);
            
            if($order['status']=='3'||$order['status']=='5'){
                $this->response(array('info'=>"申请成功"),'json',200);
            }else{
                $this->response(array('info'=>"取消成功"),'json',200);
            }
        }else{
            $this->response(array('info'=>"申请失败"),'json',400);
        }
        
        
    }
    protected function cancelOrder($order_id){
        $orderModel = D('order');
        $order_data = $orderModel->cancelOrder($order_id);
        return $order_data;
    }
     //删除订单，已取消或者已完成的订单可以删除
    public function delteOrder(){
        $uid =$this->login();
        
        $post =json_decode(file_get_contents('php://input'), true);
        //$post['order_id']=19;//
        if($post['order_id']!= null){
            $order_id = $post['order_id'];
        }else{
            $order_id = 0;
        }
        $order =M('order')
                ->where(array('uid'=>$uid,'id'=>$order_id))
                ->find();
        if($order['status']=='1'||$order['status']=='2'){
            $data['status']='2';//未支付的取消
            $data['is_delete']=1;//患者删除，
           
            $save =M('order')
                    ->where(array('uid'=>$uid,'id'=>$order_id))
                    ->save($data);
        }
        if($order['status']=='6'||$order['status']=='7'){
            //已完成的订单删除
            $data['is_delete']=1;//患者删除，
            $save =M('order')
                    ->where(array('uid'=>$uid,'id'=>$order_id))
                    ->save($data);
        }
        $this->response(array('info'=>'删除成功'),'json',200);
        
    }

}
